package com.mccken.demo.io.socket;

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

/**
 * @program: mccken-collect
 * @description:
 * @author: mccken
 * @create: 2022-04-19 10:22
 **/
public class Client {

	public static void main(String[] args) throws IOException {
		Socket socket = new Socket("localhost", 9000);
		OutputStream out = socket.getOutputStream();
		InputStreamReader in = new InputStreamReader(socket.getInputStream());

		Scanner scanner = new Scanner(System.in);
		char[] chars = new char[1024*1024];
		
		// 接收消息的任务
		Runnable runnable = new Runnable() {
			@Override
			public void run() {
				try {
					System.out.println("111");
					int len = in.read(chars);
					while (len > 0) {
						String resp = new String(chars, 0, len);
						System.out.println("服务端收到消息: " + resp);
						len = in.read(chars);
					}
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		};
		
		Runnable runnable1 = new Runnable() {
			@Override
			public void run() {
				while (scanner.hasNext()) {
					String str = scanner.nextLine();
					System.out.println("输入：" + str);
					try {
						out.write(str.getBytes(StandardCharsets.UTF_8));
					} catch (IOException e) {
						e.printStackTrace();
					}
				}	
			}
		};
		
		new Thread(runnable).start();
		new Thread(runnable1).start();
		
		
		
		
	}
}
